<template>
	<DialogBox v-model:visible="drawerVisible" :title="`${drawerProps.title}${$t('menu_form.dialog_title.menu')}`" width="700px">
		<el-form
			v-if="drawerVisible"
			ref="ruleFormRef"
			label-width="100px"
			label-suffix=" :"
			:rules="rules"
			:disabled="drawerProps.isView"
			:model="drawerProps.rowData"
			:hide-required-asterisk="drawerProps.isView"
		>
			<el-form-item :label="$t('menu_form.form_label.type')" prop="type">
				<el-radio-group style="width: 100%" v-model="drawerProps.rowData!.type">
					<el-radio-button label="menu" value="menu">{{ $t("menu_form.radio_btn.menu") }}</el-radio-button>
					<el-radio-button label="btn" value="btn">{{ $t("menu_form.radio_btn.btn") }}</el-radio-button>
					<el-radio-button label="operate" value="operate">{{ $t("menu_form.radio_btn.operate") }}</el-radio-button>
					<el-radio-button label="batch" value="batch">{{ $t("menu_form.radio_btn.batch") }}</el-radio-button>
				</el-radio-group>
			</el-form-item>
			<el-form-item :label="$t('menu_form.form_label.menuname')" prop="menuName">
				<el-input v-model="drawerProps.rowData!.menuName" :placeholder="$t('menu_form.placeholder.menuname')" />
			</el-form-item>
			<el-form-item :label="$t('menu_form.form_label.title')" prop="title">
				<el-input v-model="drawerProps.rowData!.title" :placeholder="$t('menu_form.placeholder.title')" />
			</el-form-item>
			<el-form-item :label="$t('menu_form.form_label.icon')" prop="icon">
				<el-popover :show-after="500" placement="bottom-start" :width="540" trigger="click">
					<template #reference>
						<el-input
							class="icon-input"
							v-model="drawerProps.rowData!.icon"
							:placeholder="$t('menu_form.input.placeholder')"
							@click="showSelectIcon"
							readonly
						>
							<template #prefix>
								<i :class="`curr-icon iconfont ${drawerProps.rowData!.icon}`" />
							</template>
						</el-input>
					</template>
					<icon-select ref="iconSelectRef" @selected="selected" />
				</el-popover>
			</el-form-item>
			<el-form-item :label="$t('menu_form.form_label.path')" prop="path">
				<el-input v-model="drawerProps.rowData!.path" :placeholder="$t('menu_form.placeholder.path')" />
			</el-form-item>
			<el-form-item :label="$t('menu_form.form_label.component')" prop="component">
				<el-input v-model="drawerProps.rowData!.component" :placeholder="$t('menu_form.placeholder.component')" />
			</el-form-item>
			<el-form-item :label="$t('menu_form.form_label.enable')" prop="enable">
				<el-switch v-model="drawerProps.rowData!.enable" active-value="1" inactive-value="0"></el-switch>
			</el-form-item>
			<el-form-item :label="$t('menu_form.form_label.parent_id')" prop="parentId">
				<el-tree-select
					v-model="drawerProps.rowData!.parentId"
					:data="menuList"
					check-strictly
					:placeholder="$t('menu_form.select.placeholder')"
					clearable
					class="w-full"
				/>
			</el-form-item>
			<el-form-item :label="$t('menu_form.form_label.order_num')" prop="orderNum">
				<el-input-number
					v-model="drawerProps.rowData!.orderNum"
					style="width: 100%"
					:placeholder="$t('menu_form.placeholder.order_num')"
				/>
			</el-form-item>
			<el-form-item :label="$t('menu_form.form_label.perms')" prop="perms">
				<el-input v-model="drawerProps.rowData!.perms">
					<!-- <template #suffix>
						<el-tooltip>
							<i class="iconfont iconhelp-circle" />
							<template #content>
								<div>hideFoldTree:true=不显示分组树</div>
								<div>deptAndStationTree:true=显示分组与测站树</div>
							</template>
						</el-tooltip>
					</template> -->
				</el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="drawerVisible = false">{{ $t("menu_form.footer.cancel") }}</el-button>
			<el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">{{
				$t("menu_form.footer.confirm")
			}}</el-button>
		</template>
	</DialogBox>
</template>

<script setup lang="ts" name="UserDrawer">
import { getAuthMenuListApi } from "@/api/modules/login";
import DialogBox from "@/components/DialogBox";
import IconSelect from "@/components/IconSelect/index.vue";
import { HEADER_KEY_SYSTEM } from "@/config/config";
import { MessageType } from "@/enums/messageEnum";
import { PublicStore } from "@/stores/modules/public";
import { getTreeList } from "@/utils/treeUtil";
import { showMsg, showTips } from "@/utils/util";
import { FormInstance } from "element-plus";
import { ComponentInternalInstance, getCurrentInstance, reactive, ref } from "vue";
import { MenuModel } from "../interface";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const rules = reactive({
	type: [{ required: true, message: proxy?.$t("menu_form.rules.type") }],
	menuName: [{ required: true, message: proxy?.$t("menu_form.rules.menuname") }],
	path: [{ required: true, message: proxy?.$t("menu_form.rules.path") }],
	component: [{ required: true, message: proxy?.$t("menu_form.rules.component") }]
});
interface DrawerProps {
	title: string;
	isView: boolean;
	rowData?: MenuModel;
	api?: (params: any) => Promise<any>;
	getTableList?: () => Promise<any>;
}

// drawer框状态
const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
	isView: false,
	title: ""
});

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps): Promise<void> => {
	drawerProps.value = params;
	if (params.title == proxy?.$t("menu_form.title.add")) {
		drawerProps.value.rowData!.type = "menu";
		drawerProps.value.rowData!.enable = "1";
		drawerProps.value.rowData!.orderNum = 100;
	} else {
		drawerProps.value.rowData!.type = drawerProps.value.rowData!.type.trim();
	}
	await getMenuList();
	drawerVisible.value = true;
};
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
	if (drawerProps.value.rowData?.id && drawerProps.value.rowData?.parentId == drawerProps.value.rowData?.id) {
		showMsg(proxy?.$t("menu_form.msg.submit"), MessageType.warning);
		return;
	}
	ruleFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			if (!drawerProps.value.rowData?.parentId) {
				drawerProps.value.rowData!.parentId = "0";
			}
			let { code, message } = await drawerProps.value.api!(drawerProps.value.rowData);
			let ok = showTips(
				code,
				drawerProps.value.rowData?.id ? proxy?.$t("menu_form.msg.modify") : proxy?.$t("menu_form.msg.add"),
				message
			);
			// ElMessage.success({ message: `${drawerProps.value.title}用户成功！` });
			if (ok) {
				drawerProps.value.getTableList!();
				drawerVisible.value = false;
			}
		} catch (error) {
			console.log(error);
		}
	});
};

//获取角色菜单权限
const menuList = ref<any>();
const getMenuList = async () => {
	if (drawerProps.value.rowData) {
		const { userInfo } = PublicStore();
		//按系統查
		let params: any = { username: userInfo.username };
		params[HEADER_KEY_SYSTEM] = drawerProps.value.rowData?.[HEADER_KEY_SYSTEM];
		let { result } = await getAuthMenuListApi(params);
		menuList.value = getTreeList(result.records.children, "id", "menuName", drawerProps.value.rowData.id);
	}
};
const showChooseIcon = ref<boolean>(false);
const iconSelectRef = ref<any>(null);
/** 展示下拉图标 */
const showSelectIcon = () => {
	showChooseIcon.value = !showChooseIcon.value;
	if (showChooseIcon.value) {
		iconSelectRef.value.reset();
	}
};
/** 选择图标 */
const selected = (name: string) => {
	drawerProps.value.rowData!.icon = name;
	showChooseIcon.value = false;
	(document.querySelector(".icon-input") as HTMLElement).dispatchEvent(new MouseEvent("click"));
};

defineExpose({
	acceptParams
});
</script>
